import React, { useEffect, useState } from 'react'
import styles from './css/cart-item/index.module.scss'
import { useDispatch } from 'react-redux';
import {
  increase,
  decrease,
  delCartGoods,
} from "../stores/cartSlice";
import { Cross } from '@react-vant/icons';

export default function CartItem({ item }) {
  const dispatch = useDispatch();
  // 商品金额转换为两位小数
  const [priceFix, setPriceFix] = useState(0)
  useEffect(() => {
    setPriceFix(Number(item?.price).toFixed(2))
  }, [item])

  // 单个商品总金额
  const [total, setTotal] = useState(0)
  useEffect(() => {
    setTotal((Number(item?.price) * item?.count).toFixed(2))
  }, [item])

  // 商品数量加一
  const incre = (id) => {
    dispatch(increase({ id }))
  }

  // 商品数量减一
  const decre = (id) => {
    if (item?.count == 1) {
      return
    }
    dispatch(decrease({ id }))
  }

  // 删除商品
  const delCart = (id) => {
    dispatch(delCartGoods({ id }))
  }
  return (
    <li className={styles.li}>
      <a href="#" className={styles["card-img"]}>
        <img src={"//oss.51cocoa.com/" + item?.img_url} />
      </a>
      <div className={styles["cake-right"]}>
        <p>最早配送时间 2023-02-24 09:30~10:30</p>
        <a href="#" className={styles["card-title"]}>{item?.name}</a>
        <span>规格: </span>
        <span className={styles["spec"]}>
          <span>{item?.weight > 0 ? item?.weight + 'g(' : ''}</span>
          <span>{item?.spec}</span>
          <span>{item?.weight > 0 ? ')' : ''}</span>
        </span>

      </div>
      <div className={styles["birthdayCard-check"]}>
        <input type="text" placeholder="选择生日牌" v-if="false" />
      </div>

      <div className={styles["price-part"]}>￥{priceFix}</div>
      <div className={styles["num-part"]}>
        <span onClick={() => decre(item.cake_goods_id)}>-</span>
        <span className={styles["span-num"]}>{item?.count}</span>
        <span onClick={() => incre(item.cake_goods_id)}>+</span>
      </div>
      <div className={styles["total-part"]}>￥{total}</div>
      <div className={styles["btn"]} onClick={() => delCart(item.cake_goods_id)}><Cross /></div>
    </li>
  )
}
